import React from 'react';
import { inject, observer } from 'mobx-react';
import QRCode from 'qrcode.react';

@inject('portalLoginStore')
@observer
class E9QRCode extends React.Component {
    constructor(props) {
        super(props);
        this.onRefresh = this.onRefresh.bind(this);
        this.onDownload = this.onDownload.bind(this);
    }

    componentDidMount() {
        const { portalLoginStore } = this.props;
        const { state = {} } = portalLoginStore;
        const { cacheAccount: loginId, langId } = state;
        portalLoginStore.getLoginForm({ loginId, langId }, () => portalLoginStore.onQCLoginStart());
    }

    componentWillUnmount() {
        const { portalLoginStore } = this.props;
        portalLoginStore.onQCLoginEnd();
    }

    render() {
        const { portalLoginStore } = this.props;
        const { labelObj, qrcodeIsInvalid, emobileDownloadUrl, state = {} } = portalLoginStore;
        const { loginSettingInfo = {}, qrCode } = state;
        const { loginForm = {} } = loginSettingInfo;

        const size = this.props.size || 180;
        const color = this.props.color || loginForm.color || '#fff';

        return (
            <div className="e9login-QRCode">
                <div className="e9login-QRCode-area">
                    {qrcodeIsInvalid && (
                        <div className="e9login-QRCode-timeout">
                            <div className="e9login-QRCode-timeout-mask" />
                            <div className="e9login-QRCode-timeout-tips">{labelObj.qrcodeisinvalid}</div>
                            <i className="icon-coms-Refresh e9login-QRCode-timeout-refresh" title={labelObj.refresh} onClick={this.onRefresh} />
                        </div>
                    )}
                    {qrCode.text ? <QRCode ecId={`${this && this.props && this.props.ecId || ''}_QRCode@9p5ycn`} value={qrCode.text} size={size} fgColor="#404549" bgColor="#eaeaea" /> : ''}
                </div>
                <div className="e9login-QRCode-describe" style={{ color }}>{labelObj.qrcode}</div>
                {emobileDownloadUrl && <div className="e9login-QRCode-download" style={{ color }} onClick={this.onDownload}>{labelObj.download}</div>}
            </div>
        );
    }

    onRefresh() {
        const { portalLoginStore } = this.props;
        const { state = {} } = portalLoginStore;
        const { cacheAccount: loginId, langId } = state;
        portalLoginStore.getLoginForm({ loginId, langId }, () => portalLoginStore.onQCLoginStart());
    }

    onDownload() {
        const { portalLoginStore } = this.props;
        const { emobileDownloadUrl } = portalLoginStore;
        window.open(emobileDownloadUrl);
    }
}

export default E9QRCode;
